<script setup>
import PageContainer from "@/components/AdminConponents/PageContainer.vue";
import { ref } from 'vue'
import { updatePasswordAPI } from "@/api/AdminApi/admin.js";
import { useAdminStore } from '@/stores'
import { useRouter } from 'vue-router'
import 'element-plus/theme-chalk/el-message.css'
import { ElMessage } from "element-plus"

const pwdForm = ref({
  oldPwd: '',
  newPwd: '',
  rePwd: ''
})
const pwdFormRef = ref()

const rules = {
  oldPwd: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 6, max: 15, message: '密码长度必须在6到15位之间', trigger: 'blur' }
  ],
  newPwd: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 15, message: '密码长度必须在6到15位之间', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value === pwdForm.value.oldPwd) {
          callback(new Error('新密码不能与原密码相同'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  rePwd: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { min: 6, max: 15, message: '密码长度必须在6到15位之间', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== pwdForm.value.newPwd) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const adminStore = useAdminStore()
const router = useRouter()
const submitForm = async () => {
  await pwdFormRef.value.validate()
  const res = await updatePasswordAPI(pwdForm.value)
  if (res.code === 1) {
    ElMessage.success('修改密码成功')
    // 密码修改成功后，退出重新登录
    // 1. 清空本地存储的 token 和个人信息
    adminStore.setToken('')
    adminStore.setAdminInfo({})
    router.push('/admin/login')
  } else {
    ElMessage.error(res.msg)
  }

}

</script>

<template>
  <page-container title="修改密码">
    <el-row>
      <el-col :sapn="12">
        <el-form
            ref="pwdFormRef"
            :model="pwdForm"
            :rules="rules"
            label-width="100px">
          <el-form-item class="item" label="原密码" prop="oldPwd">
            <el-input v-model="pwdForm.oldPwd" type="password"></el-input>
          </el-form-item>
          <el-form-item class="item" label="新密码" prop="newPwd">
            <el-input v-model="pwdForm.newPwd" type="password"></el-input>
          </el-form-item>
          <el-form-item class="item" label="确认密码" prop="rePwd">
            <el-input v-model="pwdForm.rePwd" type="password"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm">修改密码</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </page-container>
</template>

<style scoped>
.item {
  width: 500px;
}
</style>
